

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Moe Wang">
  <meta name="keywords" content="">
  
    <meta name="description" content="纯函数（Pure Function） 简单说，一个函数的返回结果只依赖于他的参数，并且执行过程中没有副作用，就是纯函数  从上面看，纯函数需要两个条件：  函数的返回结果只依赖于它的参数 函数的执行过程没有副作用  现在分别看一下两个条件  函数的返回结果只依赖于它的参数 123const a &#x3D; 1const foo &#x3D; (b) &#x3D;&gt; a + bfoo(2) &#x2F;&#x2F; &#x3D;&gt; 3  foo">
<meta property="og:type" content="article">
<meta property="og:title" content="实现MyRedux（二）">
<meta property="og:url" content="https://moewang0321.github.io/2019/12/04/2019-12-04-Redux%EF%BC%88%E4%BA%8C%EF%BC%89/index.html">
<meta property="og:site_name" content="moe_大杂烩">
<meta property="og:description" content="纯函数（Pure Function） 简单说，一个函数的返回结果只依赖于他的参数，并且执行过程中没有副作用，就是纯函数  从上面看，纯函数需要两个条件：  函数的返回结果只依赖于它的参数 函数的执行过程没有副作用  现在分别看一下两个条件  函数的返回结果只依赖于它的参数 123const a &#x3D; 1const foo &#x3D; (b) &#x3D;&gt; a + bfoo(2) &#x2F;&#x2F; &#x3D;&gt; 3  foo">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2019/12/04/yVTaFHuE2KC4blI.png">
<meta property="og:image" content="https://i.loli.net/2019/12/04/IEWhwaOTZlSpvN8.png">
<meta property="og:image" content="https://i.loli.net/2019/12/04/e6KNOS8A5ipxVvk.png">
<meta property="og:image" content="https://i.loli.net/2019/12/04/CE9rWDcVh7fS1vA.png">
<meta property="article:published_time" content="2019-12-04T12:09:16.000Z">
<meta property="article:modified_time" content="2023-02-14T08:06:39.751Z">
<meta property="article:author" content="Moe Wang">
<meta property="article:tag" content="React">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://i.loli.net/2019/12/04/yVTaFHuE2KC4blI.png">
  
  
  
  <title>实现MyRedux（二） - moe_大杂烩</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"moewang0321.github.io","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>moe_大杂烩</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="实现MyRedux（二）"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2019-12-04 20:09" pubdate>
          2019年12月4日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          43 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">实现MyRedux（二）</h1>
            
            
              <div class="markdown-body">
                
                <h3 id="纯函数（Pure-Function）"><a href="#纯函数（Pure-Function）" class="headerlink" title="纯函数（Pure Function）"></a>纯函数（Pure Function）</h3><blockquote>
<p>简单说，<strong>一个函数的返回结果只依赖于他的参数，并且执行过程中没有副作用</strong>，就是纯函数</p>
</blockquote>
<p>从上面看，纯函数需要两个条件：</p>
<ul>
<li>函数的返回结果只依赖于它的参数</li>
<li>函数的执行过程没有副作用</li>
</ul>
<p>现在分别看一下两个条件</p>
<ol>
<li><p><strong>函数的返回结果只依赖于它的参数</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">foo</span> = (<span class="hljs-params">b</span>) =&gt; a + b<br><span class="hljs-title function_">foo</span>(<span class="hljs-number">2</span>) <span class="hljs-comment">// =&gt; 3</span><br></code></pre></td></tr></table></figure>

<p><code>foo</code>就不是一个纯函数，因为他的返回值要依赖外部变量<code>a</code>，我们不知道<code>a</code>的情况下，不能保证<code>foo(2)</code>的返回值是3，如果<code>a</code>变化，那返回值是<strong>不可预料</strong>的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">foo</span> = (<span class="hljs-params">x, b</span>) =&gt; x + b<br><span class="hljs-title function_">foo</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>) <span class="hljs-comment">// =&gt; 3</span><br></code></pre></td></tr></table></figure>

<p>修改一下<code>foo</code>，现在函数的返回结果只依赖于他的参数，所以是纯函数</p>
</li>
<li><p><strong>函数执行过程没有副作用</strong></p>
</li>
</ol>
<p>再修改一下<code>foo</code></p>
   <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">foo</span> = (<span class="hljs-params">obj, b</span>) =&gt; &#123;<br>  <span class="hljs-keyword">return</span> obj.<span class="hljs-property">x</span> + b<br>&#125;<br><span class="hljs-keyword">const</span> counter = &#123; <span class="hljs-attr">x</span>: <span class="hljs-number">1</span> &#125;<br><span class="hljs-title function_">foo</span>(counter, <span class="hljs-number">2</span>) <span class="hljs-comment">// =&gt; 3</span><br>counter.<span class="hljs-property">x</span> <span class="hljs-comment">// =&gt; 1</span><br></code></pre></td></tr></table></figure>

<p>   把原来的x变成了一个对象，可以往里面传一个对象进行计算，过程中不会对传入的对象进行更改，<code>counter</code>不会发生变化，所以是纯函数，但是如果我们稍微修改它一下：</p>
   <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">foo</span> = (<span class="hljs-params">obj, b</span>) =&gt; &#123;<br>  obj.<span class="hljs-property">x</span> = <span class="hljs-number">2</span><br>  <span class="hljs-keyword">return</span> obj.<span class="hljs-property">x</span> + b<br>&#125;<br><span class="hljs-keyword">const</span> counter = &#123; <span class="hljs-attr">x</span>: <span class="hljs-number">1</span> &#125;<br><span class="hljs-title function_">foo</span>(counter, <span class="hljs-number">2</span>) <span class="hljs-comment">// =&gt; 4</span><br>counter.<span class="hljs-property">x</span> <span class="hljs-comment">// =&gt; 2</span><br></code></pre></td></tr></table></figure>

<p>   在<code>foo</code>内部添加了一句<code>obj.x = 2</code>，计算前<code>counter.x</code>是1，但是计算以后的<code>counter.x</code>是2。函数内的执行对外部产生了影响，也叫<strong>副作用</strong>，所以不是纯函数</p>
<p>   只要函数执行产生了<strong>外部可以观察到的变化</strong>,就是副作用，像调用DOM API修改页面，发送AJAX请求，甚至<code>console.log</code>也是副作用</p>
<hr>
<h3 id="优化共享结构的对象"><a href="#优化共享结构的对象" class="headerlink" title="优化共享结构的对象"></a>优化共享结构的对象</h3><p>其实之前的部分已经可以算是简单实现了一个redux，但是如果细心就会发现，之前的版本中有很严重的性能问题，如果我们试着在每个渲染函数开头输出一些日志看一下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">renderApp</span> (appState) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;render app...&#x27;</span>)<br>  <span class="hljs-title function_">renderTitle</span>(appState.<span class="hljs-property">title</span>)<br>  <span class="hljs-title function_">renderContent</span>(appState.<span class="hljs-property">content</span>)<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">renderTitle</span> (title) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;render title...&#x27;</span>)<br>  <span class="hljs-keyword">const</span> titleDOM = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;title&#x27;</span>)<br>  titleDOM.<span class="hljs-property">innerHTML</span> = title.<span class="hljs-property">text</span><br>  titleDOM.<span class="hljs-property">style</span>.<span class="hljs-property">color</span> = title.<span class="hljs-property">color</span><br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">renderContent</span> (content) &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;render content...&#x27;</span>)<br>  <span class="hljs-keyword">const</span> contentDOM = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;content&#x27;</span>)<br>  contentDOM.<span class="hljs-property">innerHTML</span> = content.<span class="hljs-property">text</span><br>  contentDOM.<span class="hljs-property">style</span>.<span class="hljs-property">color</span> = content.<span class="hljs-property">color</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>执行一次初始化渲染和两次更新</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> store = <span class="hljs-title function_">createStore</span>(appState, stateChanger)<br>store.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-title function_">renderApp</span>(store.<span class="hljs-title function_">getState</span>())) <span class="hljs-comment">// 监听数据变化</span><br><br><span class="hljs-title function_">renderApp</span>(store.<span class="hljs-title function_">getState</span>()) <span class="hljs-comment">// 首次渲染页面</span><br>store.<span class="hljs-title function_">dispatch</span>(&#123; <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;UPDATE_TITLE_TEXT&#x27;</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">&#x27;React.js&#x27;</span> &#125;) <span class="hljs-comment">// 修改标题文本</span><br>store.<span class="hljs-title function_">dispatch</span>(&#123; <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;UPDATE_TITLE_COLOR&#x27;</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">&#x27;blue&#x27;</span> &#125;) <span class="hljs-comment">// 修改标题颜色</span><br></code></pre></td></tr></table></figure>

<p>在控制塔瞄一眼呗：</p>
<p><img src="https://i.loli.net/2019/12/04/yVTaFHuE2KC4blI.png" srcset="/img/loading.gif" lazyload></p>
<p>看得出来一组三个render函数输出了三次，第一次肯定是首次渲染，后边两次分别是两次<code>store.dispatch</code>导致的。可以看出每次更新数据都要重新渲染整个App，但是我们两次更新都只是更新了<code>title</code>字段，并不需要重新调用<code>renderContent</code>，它是一个冗余的操作，现在需要优化它</p>
<p>提出一种解决方法（但不限于一种），在每个渲染函数调用之前判断一下传入的数据和旧数据是否相同，相同就不调用了</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">renderApp</span> (newAppState, oldAppState = &#123;&#125;) &#123; <span class="hljs-comment">// 防止 oldAppState 没有传入，所以加了默认参数 oldAppState = &#123;&#125;</span><br>  <span class="hljs-keyword">if</span> (newAppState === oldAppState) <span class="hljs-keyword">return</span> <span class="hljs-comment">// 数据没有变化就不渲染了</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;render app...&#x27;</span>)<br>  <span class="hljs-title function_">renderTitle</span>(newAppState.<span class="hljs-property">title</span>, oldAppState.<span class="hljs-property">title</span>)<br>  <span class="hljs-title function_">renderContent</span>(newAppState.<span class="hljs-property">content</span>, oldAppState.<span class="hljs-property">content</span>)<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">renderTitle</span> (newTitle, oldTitle = &#123;&#125;) &#123;<br>  <span class="hljs-keyword">if</span> (newTitle === oldTitle) <span class="hljs-keyword">return</span> <span class="hljs-comment">// 数据没有变化就不渲染了</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;render title...&#x27;</span>)<br>  <span class="hljs-keyword">const</span> titleDOM = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;title&#x27;</span>)<br>  titleDOM.<span class="hljs-property">innerHTML</span> = newTitle.<span class="hljs-property">text</span><br>  titleDOM.<span class="hljs-property">style</span>.<span class="hljs-property">color</span> = newTitle.<span class="hljs-property">color</span><br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">renderContent</span> (newContent, oldContent = &#123;&#125;) &#123;<br>  <span class="hljs-keyword">if</span> (newContent === oldContent) <span class="hljs-keyword">return</span> <span class="hljs-comment">// 数据没有变化就不渲染了</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;render content...&#x27;</span>)<br>  <span class="hljs-keyword">const</span> contentDOM = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;content&#x27;</span>)<br>  contentDOM.<span class="hljs-property">innerHTML</span> = newContent.<span class="hljs-property">text</span><br>  contentDOM.<span class="hljs-property">style</span>.<span class="hljs-property">color</span> = newContent.<span class="hljs-property">color</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>然后用一个<code>oldState</code> 来保存旧的应用状态，在需要重新渲染的地方把新旧数据传进去：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> store = <span class="hljs-title function_">createStore</span>(appState, stateChanger)<br><span class="hljs-keyword">let</span> oldState = store.<span class="hljs-title function_">getState</span>() <span class="hljs-comment">// 缓存旧的 state</span><br>store.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-keyword">const</span> newState = store.<span class="hljs-title function_">getState</span>() <span class="hljs-comment">// 数据可能变化，获取新的 state</span><br>  <span class="hljs-title function_">renderApp</span>(newState, oldState) <span class="hljs-comment">// 把新旧的 state 传进去渲染</span><br>  oldState = newState <span class="hljs-comment">// 渲染完以后，新的 newState 变成了旧的 oldState，等待下一次数据变化重新渲染</span><br>&#125;)<br>...<br></code></pre></td></tr></table></figure>

<p>可别以为这样就好了……，看看<code>stateChanger</code>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">stateChanger</span> (state, action) &#123;<br>  <span class="hljs-keyword">switch</span> (action.<span class="hljs-property">type</span>) &#123;<br>    <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;UPDATE_TITLE_TEXT&#x27;</span>:<br>      state.<span class="hljs-property">title</span>.<span class="hljs-property">text</span> = action.<span class="hljs-property">text</span><br>      <span class="hljs-keyword">break</span><br>    <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;UPDATE_TITLE_COLOR&#x27;</span>:<br>      state.<span class="hljs-property">title</span>.<span class="hljs-property">color</span> = action.<span class="hljs-property">color</span><br>      <span class="hljs-keyword">break</span><br>    <span class="hljs-attr">default</span>:<br>      <span class="hljs-keyword">break</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>即使修改了<code>state.title.text</code>，但是<code>state</code>还是原来那个<code>state</code>，一切都是以前的一切，这些引用指向的还是于谦的对象，只是内容改变了而已，就像下边这个语句：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">let</span> obj = &#123;<br>	<span class="hljs-attr">x</span>: <span class="hljs-number">0</span><br>&#125;<br><span class="hljs-keyword">let</span> obj2 = obj<br>obj2.<span class="hljs-property">x</span> = <span class="hljs-number">1</span><br>obj !== obj2 <span class="hljs-comment">// false ,两个引用指向同一个对象,怎么会不相等？</span><br></code></pre></td></tr></table></figure>

<p>想让两者成为两个完全不同的对象，就得使用ES6的语法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> obj = &#123;<span class="hljs-attr">a</span>:<span class="hljs-number">1</span>&#125;<br><span class="hljs-keyword">const</span> obj2 = &#123;...obj&#125;<br></code></pre></td></tr></table></figure>

<p>放到例子中就是</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">let</span> newAppState = &#123; <span class="hljs-comment">// 新建一个 newAppState</span><br>  ...appState, <span class="hljs-comment">// 复制 appState 里面的内容</span><br>  <span class="hljs-attr">title</span>: &#123; <span class="hljs-comment">// 用一个新的对象覆盖原来的 title 属性</span><br>    ...appState.<span class="hljs-property">title</span>, <span class="hljs-comment">// 复制原来 title 对象里面的内容</span><br>    <span class="hljs-attr">text</span>: <span class="hljs-string">&#x27;new text&#x27;</span> <span class="hljs-comment">// 覆盖 text 属性</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>用一个图来表示对象结构</p>
<p><img src="https://i.loli.net/2019/12/04/IEWhwaOTZlSpvN8.png" srcset="/img/loading.gif" lazyload></p>
<p><code>appState</code>和<code>newAppState</code>是两个不同的对象，因为浅复制所以两个对象的<code>content</code>指向同一对象，但是<code>title</code>被一个新的对象覆盖，所以指向不同，同样的可修改<code>appState.title.color</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">let</span> newAppState1 = &#123; <span class="hljs-comment">// 新建一个 newAppState1</span><br>  ...newAppState, <span class="hljs-comment">// 复制 newAppState1 里面的内容</span><br>  <span class="hljs-attr">title</span>: &#123; <span class="hljs-comment">// 用一个新的对象覆盖原来的 title 属性</span><br>    ...newAppState.<span class="hljs-property">title</span>, <span class="hljs-comment">// 复制原来 title 对象里面的内容</span><br>    <span class="hljs-attr">color</span>: <span class="hljs-string">&quot;blue&quot;</span> <span class="hljs-comment">// 覆盖 color 属性</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://i.loli.net/2019/12/04/e6KNOS8A5ipxVvk.png" srcset="/img/loading.gif" lazyload></p>
<p>这样每次我们修改某些数据的时候，都不会碰原来的数据，每次都是copy的一个新对象。现在我们可以修改<code>stateChanger</code>中的代码，让他产生上述共享结构的对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">stateChanger</span> (state, action) &#123;<br>  <span class="hljs-keyword">switch</span> (action.<span class="hljs-property">type</span>) &#123;<br>    <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;UPDATE_TITLE_TEXT&#x27;</span>:<br>      <span class="hljs-keyword">return</span> &#123; <span class="hljs-comment">// 构建新的对象并且返回</span><br>        ...state,<br>        <span class="hljs-attr">title</span>: &#123;<br>          ...state.<span class="hljs-property">title</span>,<br>          <span class="hljs-attr">text</span>: action.<span class="hljs-property">text</span><br>        &#125;<br>      &#125;<br>    <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;UPDATE_TITLE_COLOR&#x27;</span>:<br>      <span class="hljs-keyword">return</span> &#123; <span class="hljs-comment">// 构建新的对象并且返回</span><br>        ...state,<br>        <span class="hljs-attr">title</span>: &#123;<br>          ...state.<span class="hljs-property">title</span>,<br>          <span class="hljs-attr">color</span>: action.<span class="hljs-property">color</span><br>        &#125;<br>      &#125;<br>    <span class="hljs-attr">default</span>:<br>      <span class="hljs-keyword">return</span> state <span class="hljs-comment">// 没有修改，返回原来的对象</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">createStore</span> (state, stateChanger) &#123;<br>  <span class="hljs-keyword">const</span> listeners = []<br>  <span class="hljs-keyword">const</span> <span class="hljs-title function_">subscribe</span> = (<span class="hljs-params">listener</span>) =&gt; listeners.<span class="hljs-title function_">push</span>(listener)<br>  <span class="hljs-keyword">const</span> <span class="hljs-title function_">getState</span> = (<span class="hljs-params"></span>) =&gt; state<br>  <span class="hljs-keyword">const</span> <span class="hljs-title function_">dispatch</span> = (<span class="hljs-params">action</span>) =&gt; &#123;<br>    state = <span class="hljs-title function_">stateChanger</span>(state, action) <span class="hljs-comment">// 覆盖原对象</span><br>    listeners.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">listener</span>) =&gt;</span> <span class="hljs-title function_">listener</span>())<br>  &#125;<br>  <span class="hljs-keyword">return</span> &#123; getState, dispatch, subscribe &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>现在再看一眼控制台：</p>
<p><img src="https://i.loli.net/2019/12/04/CE9rWDcVh7fS1vA.png" srcset="/img/loading.gif" lazyload></p>
<p>这样我们就能避免不需要的渲染了！过两天再往下走……</p>
<hr>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/study/" class="category-chain-item">study</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/React/">#React</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>实现MyRedux（二）</div>
      <div>https://moewang0321.github.io/2019/12/04/2019-12-04-Redux（二）/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Moe Wang</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2019年12月4日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2019/12/16/2019-12-16-immutable.js/" title="immutable.js">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">immutable.js</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2019/12/03/2019-12-03-Redux%EF%BC%88%E4%B8%80%EF%BC%89/" title="实现MyRedux（一）">
                        <span class="hidden-mobile">实现MyRedux（一）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
    <div id="giscus" class="giscus"></div>
    <script type="text/javascript">
      Fluid.utils.loadComments('#giscus', function() {
        var options = {"repo":"moewang0321/moewang0321.github.io","repo-id":"MDEwOlJlcG9zaXRvcnkyMDEyNDI0NTY=","category":"Show and tell","category-id":"DIC_kwDOC_63WM4CUMsH","theme-light":"light_protanopia","theme-dark":"dark_dimmed","mapping":"pathname","reactions-enabled":1,"emit-metadata":1,"input-position":"top","loading":"lazy","lang":"zh-CN"};
        var attributes = {};
        for (let option in options) {
          if (!option.startsWith('theme-')) {
            var key = option.startsWith('data-') ? option : 'data-' + option;
            attributes[key] = options[option];
          }
        }
        var light = 'light_protanopia';
        var dark = 'dark_dimmed';
        window.GiscusThemeLight = light;
        window.GiscusThemeDark = dark;
        attributes['data-theme'] = document.documentElement.getAttribute('data-user-color-scheme') === 'dark' ? dark : light;
        for (let attribute in attributes) {
          var value = attributes[attribute];
          if (value === undefined || value === null || value === '') {
            delete attributes[attribute];
          }
        }
        var s = document.createElement('script');
        s.setAttribute('src', 'https://giscus.app/client.js');
        s.setAttribute('crossorigin', 'anonymous');
        for (let attribute in attributes) {
          s.setAttribute(attribute, attributes[attribute]);
        }
        var ss = document.getElementsByTagName('script');
        var e = ss.length > 0 ? ss[ss.length - 1] : document.head || document.documentElement;
        e.parentNode.insertBefore(s, e.nextSibling);
      });
    </script>
    <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
